//declare question arr
var question = null;
// declare answer arr
var answer = null;
//user answer option
var user_daan = ["F"];

// declare total number of question
// number of total question
var total = 0;
var score = 0;
var mobile_submit = false;
var timer1, timer2, timer3, timer4;

// 远程背景图片路径
var picAbsPath = "";

function getdatafromStr(str, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = str.substr(str.indexOf("\?") + 1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

function switchPage(pageName) {
	var images = "res/indexbg.jpg";
	if (pageName == "index") {
		images = "res/indexbg.jpg";
	}
	else if (pageName == "employee") {
		images = "res/indexbg.jpg";
	}
	else if (pageName == "share") {
		images = "res/indexbg.jpg";
	}
	else if (pageName == "question") {
		images = "res/indexbg.jpg";
	}
	 
	$('.main').css('background-image', "url(" + picAbsPath + ")");
	
	var selector = ".main ." + pageName;
	$(selector).show().siblings("div").hide();
}


//initializtion index page
function initIndexPage() {
	var param = getdatafromStr(location.href, "a");
	console.log(param);
	$.ajax({
		type: 'GET',
		url: '/question-server/activity/q/' + param, 
		dataType: 'json', 
		data: {}, 
		cache: false, 
		success: function (obj) {
			var activityPicture = obj.data.activityPicture;
			picAbsPath = location.protocol + '//' + location.hostname + location.port + '/question-static/images/' + activityPicture;
			console.log(picAbsPath);
			switchPage('index');

			if (obj.code == "000000") {
				var new_answers = [];
				new_answers.push("");
				var new_question = [];
				new_question.push({});
				for (var i=0; i<obj.data.questions.length; i++) {
					var q = obj.data.questions[i];
					var desc = q.questionName;
					var choices = [];
					for (var j=0; j<q.questionAnswer.length; j++) {
						var a = q.questionAnswer[j];
						var per_answer = {
							key: j,
							content: a.answer_content
						};
						if (a.flag == "1") {
							new_answers.push(j);
						}
						choices.push(per_answer);
					}
					var item = {
						choices: choices,
						desc: desc
					};
					new_question.push(item);
				}
				question = new_question;
				answer = new_answers
				total = answer.length -1;
			}

		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//mobile_submit=false;	
		}
	});
	
	
	$("#totalNo").text(total);
}


//the function of jump to next question
function nextQuestion() {
	if (parseFloat($("#currentNo").text()) < total) {
		$("#currentNo").text(parseFloat($("#currentNo").text()) + 1);
		var currentNo = parseFloat($("#currentNo").text());
		$("#questionTitle").text(question[currentNo].desc);
		$("#questionList li").each(function () {
			var index = $(this).index();
			//$(this).hide();//hide title_detail
			if (question[currentNo].choices[index]) {
				$(this).show();//show title_detail
				$(this).find("span").text(question[currentNo].choices[index].content);
			} else {
				$(this).hide();
			}
		});
		$("#dd").text("30");
		return false;
	} else {//jump to result page answer over
		initScorePage();
		clearInterval(timer1);
	}
}

function startTest() {
	switchPage("question");
	$(".question-dialog").jumpBox(true);

	// declare the score of tester
	score = 0;
	// load first question
	$("#totalNo").text(total);
	$("#currentNo").text("1");
	$("#questionTitle").text(question[1].desc);
	$("#questionList li").each(function () {
		var index = $(this).index();
		//has no<4
		if (question[1].choices[index]) {
			$(this).find("span").text(question[1].choices[index].content);
		} else {
			$(this).hide();
		}

	});
	$("#dd").text("30");
	//the countdown begin, jump to next question when finished
	timer1 = window.setInterval(function () {
		var s = document.getElementById("dd");;
		if (s.innerHTML == 0) {
			//time out answer
			user_daan.push("Z");
			nextQuestion();
			return false;
		} else {
			s.innerHTML = s.innerHTML * 1 - 1;
		}
	}, 1000);
	// when tester click the choice
	$(".option ul li").click(function () {
		var $_this = $(this);
		//get the number of question
		var questionNo = parseFloat($_this.parents(".question-dialog").find("h2 span.index #currentNo").text());
		//get selection options
		var questionAnswer = $_this.find("em").text();
		//change the state of the option
		if (!$_this.hasClass("active")) {
			$_this.addClass("active").siblings().removeClass("active");
			//show right or wrong after half a second
			timer2 = setTimeout(function () {
				//insert user answer
				user_daan.push(questionAnswer);
				// right
				if (answer[questionNo] == questionAnswer) {
					if ((questionNo & 1) === 1) {
						$_this.parents(".popInner").addClass("right_1");
					} else {
						$_this.parents(".popInner").addClass("right_0");
					}
					timer3 = setTimeout(function () {
						if ((questionNo & 1) === 1) {
							$_this.parents(".popInner").removeClass("right_1");
						} else {
							$_this.parents(".popInner").removeClass("right_0");
						}

						$_this.removeClass("active");
						score ++;
						// get a pointscore++;
						nextQuestion();
					}, 3000);
				} else {
					//wrong
					if ((questionNo & 1) === 1) {
						$_this.parents(".popInner").addClass("wrong_1");
					} else {
						$_this.parents(".popInner").addClass("wrong_0");
					}
					timer4 = setTimeout(function () {
						if ((questionNo & 1) === 1) {
							$_this.parents(".popInner").removeClass("wrong_1");
						} else {
							$_this.parents(".popInner").removeClass("wrong_0");
						}
						$_this.removeClass("active");
						nextQuestion();
					}, 3000);
				}
			}, 500);
		}
	});
}

// 分享朋友圈
function createShareWechat() {
	$('.wechat_share_guide').show();

	$('.wechat_share_guide').bind('click', function(e) {
		$(this).hide();
	});
}

// 生成分享二维码
function createShareQRcode() {
	var employee_id = $.trim($('#employee_id').val());
	if (employee_id == "输入工号ID") {
		alert('输入工号ID');
		return;
	}
	else {
		var url = "http://answer.hmccb.com/" + "?empid=" + employee_id;
		$('#emp_id').text(employee_id);

		// 获取二维码图片
		var qrcode = new QRCode(document.getElementById("qrcode"), {
			text: url,
			width: 100,
			height: 100,
			colorDark : "#000000",
			colorLight : "#ffffff",
			correctLevel : QRCode.CorrectLevel.H
		});
		var c = document.querySelector('#qrcode>canvas');
		var imgData = c.toDataURL("image/png");
		$('#qrcode').hide();

		// 准备二维码背景
		switchPage('share');
		
		// 将获取到的二维码内容和背景合成
		$('#img_qrcode').attr('src', imgData);

		
		// 生成图片
		html2canvas(document.body,{
			// options
		}).then(function(canvas){
			var imgBase64 = canvas.toDataURL();
			
			// 切换到员工通道界面
			switchPage('employee');
			
			// 展示合成后的二维码
			$('#img_qrcode_result').attr('src', imgBase64);
			$('#show_result').show();
			
			// 将二维码滚到到最下方
			setTimeout(function() {
				var elm = document.getElementById('show_result');
				elm.scrollTop = elm.scrollHeight;
			}, 1000);

			// 展示用户引导信息
			$('.qrcode_save_guide').show();
			$('.qrcode_save_guide').bind('click', function(e) {
				$(this).hide();
			});

		});
		
	}
}

function userShare() {
	window.location.href="res/share-qrcode.jpg";
}

//检查手机号
function checkPhone(value) {
	if (value.length == 0) {
		return '手机号不能为空～';
	} else if (/^0?1[3|4|5|7|8][0-9]\d{8}$/.test(value)) {
		return '';
	} else {
		return '您输入的手机号有误～';
	}
}

//initializtion score result page
function initScorePage() {
	switchPage("result");

	$(".popWrap").hide();
	$("#rightNo").text(score);
	$("#wrongNo").text(total - score);
	if (total - score == 0) {
		$("#show_tip_0").html("特授予“学霸称号”");
	}

}


function initRankPage() {
	$(".main .content.rank").show().siblings(".content").hide();
	//$(".main img.rank").show().siblings("img").hide();
	//$(".main .list").height($(window).height()-6);
	$("#paihang").empty();
	$.ajax({
		url: '../top10.json', dataType: 'json', data: { open_id: 1 }, cache: false, type: 'GET',
		success: function (obj) {
			var str_html = "";
			$.each(obj, function (i, val) {
				str_html = str_html + '<dt>' + val.area + '</dt>'
					+ '<dd>'
					+ '<div class="answerNumber clearfix">'
					+ '<div class="bar fl">'
					+ '<div style="width:' + val.a1 + ';"></div>'
					+ '</div>'
					+ '<div class="num fr"><span>' + val.a2 + '</span>人</div>'
					+ '</div>'
					+ '<div class="trueNumber clearfix">'
					+ '<div class="bar fl">'
					+ '<div style="width:' + val.b1 + '"></div>'
					+ '</div>'
					+ '<div class="num fr"><span>' + val.b2 + '人</span></div>'
					+ '</div>'
					+ '</dd>';
				//  				var jp_str =(i+1)+"、"+val.fav_name;
				//  				$("<p/>").appendTo(".paihang").html(jp_str);
			});
			//alert(str_html);
			document.getElementById("paihang").innerHTML = str_html;
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
		}
	});
	$(".main .list dl").height($(window).height() - $(".main .list > img").height() - 30);
}
